<template>
  <div class="data-dictionary-management">
    <div class="page-header">
      <h1>数据字典管理</h1>
      <p class="page-description">管理数据字典定义，为数据字段提供标准化的数据类型、格式和约束规范</p>
    </div>

    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate" :icon="Plus">
          新建数据字典
        </el-button>
        <el-button @click="refreshData" :icon="Refresh" :loading="loading">
          刷新
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-select
          v-model="selectedDomain"
          placeholder="筛选数据域"
          clearable
          style="width: 150px; margin-right: 12px"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="domain in dataDomains"
            :key="domain.code"
            :label="domain.name"
            :value="domain.code"
          />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索数据字典..."
          clearable
          style="width: 300px"
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>
    </div>

    <el-table
      :data="filteredDataDictionaries"
      v-loading="loading"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="code" label="字典编码" width="150" />
      <el-table-column prop="name" label="字典名称" width="180" />
      <el-table-column prop="domainCode" label="所属数据域" width="120">
        <template #default="{ row }">
          <el-tag type="primary" size="small">{{ getDomainName(row.domainCode) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="dataType" label="数据类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getDataTypeColor(row.dataType)" size="small">{{ row.dataType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="length" label="长度" width="80" />
      <el-table-column prop="description" label="描述" min-width="200" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editDataDictionary(row)">
            编辑
          </el-button>
          <el-button 
            :type="row.status === 'active' ? 'warning' : 'success'" 
            size="small" 
            @click="toggleStatus(row)"
          >
            {{ row.status === 'active' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" size="small" @click="deleteDataDictionary(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />

    <!-- 创建/编辑数据字典对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑数据字典' : '新建数据字典'"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字典编码" prop="code">
              <el-input
                v-model="formData.code"
                placeholder="如：USER_NAME、PHONE_NUMBER"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典名称" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="如：用户姓名、手机号码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属数据域" prop="domainCode">
              <el-select v-model="formData.domainCode" placeholder="请选择数据域" style="width: 100%">
                <el-option
                  v-for="domain in dataDomains"
                  :key="domain.code"
                  :label="domain.name"
                  :value="domain.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据类型" prop="dataType">
              <el-select v-model="formData.dataType" placeholder="请选择数据类型" style="width: 100%">
                <el-option label="VARCHAR" value="VARCHAR" />
                <el-option label="CHAR" value="CHAR" />
                <el-option label="TEXT" value="TEXT" />
                <el-option label="INT" value="INT" />
                <el-option label="BIGINT" value="BIGINT" />
                <el-option label="DECIMAL" value="DECIMAL" />
                <el-option label="DATETIME" value="DATETIME" />
                <el-option label="DATE" value="DATE" />
                <el-option label="BOOLEAN" value="BOOLEAN" />
                <el-option label="JSON" value="JSON" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="长度">
              <el-input-number
                v-model="formData.length"
                :min="1"
                :max="65535"
                placeholder="字段长度"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="精度">
              <el-input-number
                v-model="formData.precision"
                :min="0"
                :max="65"
                placeholder="小数精度"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否必填">
              <el-switch v-model="formData.required" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入数据字典的详细描述"
          />
        </el-form-item>
        
        <el-form-item label="格式规则">
          <el-input
            v-model="formData.pattern"
            placeholder="正则表达式，如：^1[3-9]\d{9}$"
          />
          <div class="form-tip">用于数据验证的正则表达式</div>
        </el-form-item>
        
        <el-form-item label="默认值">
          <el-input
            v-model="formData.defaultValue"
            placeholder="字段的默认值"
          />
        </el-form-item>
        
        <el-form-item label="示例值">
          <el-input
            v-model="formData.example"
            placeholder="字段的示例值"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import { dataDictionaryApi } from '@/api/dataDictionary.js'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const selectedDomain = ref('')
const formRef = ref()

// 数据域列表（从数据域管理获取）
const dataDomains = ref([
  { code: 'USER', name: '用户域' },
  { code: 'PRODUCT', name: '商品域' },
  { code: 'ORDER', name: '订单域' },
  { code: 'SYSTEM', name: '系统域' }
])

// 数据字典数据
const dataDictionaries = ref([])
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  code: '',
  name: '',
  domainCode: '',
  dataType: '',
  length: null,
  precision: null,
  required: false,
  description: '',
  pattern: '',
  defaultValue: '',
  example: '',
  status: 'active'
})

// 表单验证规则
const formRules = {
  code: [
    { required: true, message: '请输入字典编码', trigger: 'blur' },
    { pattern: /^[A-Z][A-Z0-9_]*$/, message: '编码只能包含大写字母、数字和下划线，且以大写字母开头', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入字典名称', trigger: 'blur' }
  ],
  domainCode: [
    { required: true, message: '请选择所属数据域', trigger: 'change' }
  ],
  dataType: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const filteredDataDictionaries = computed(() => {
  let filtered = dataDictionaries.value

  // 按数据域筛选
  if (selectedDomain.value) {
    filtered = filtered.filter(dict => dict.domainCode === selectedDomain.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(dict => 
      dict.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      dict.code.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  return filtered
})

// 方法
const getDomainName = (domainCode) => {
  const domain = dataDomains.value.find(d => d.code === domainCode)
  return domain ? domain.name : domainCode
}

const getDataTypeColor = (dataType) => {
  const colors = {
    VARCHAR: 'primary',
    CHAR: 'primary',
    TEXT: 'primary',
    INT: 'success',
    BIGINT: 'success',
    DECIMAL: 'warning',
    DATETIME: 'info',
    DATE: 'info',
    BOOLEAN: 'danger',
    JSON: 'purple'
  }
  return colors[dataType] || 'info'
}

const formatDateTime = (dateTime) => {
  return dateTime
}

const showCreateDialog = () => {
  dialogVisible.value = true
  isEdit.value = false
  // 重置表单
  Object.assign(formData, {
    code: '',
    name: '',
    domainCode: '',
    dataType: 'VARCHAR',
    length: null,
    precision: null,
    required: true,
    description: '',
    pattern: '',
    defaultValue: '',
    example: ''
  })
}

const handleEdit = (row) => {
  dialogVisible.value = true
  isEdit.value = true
  // 填充表单数据
  Object.assign(formData, {
    id: row.id,
    code: row.code,
    name: row.name,
    domainCode: row.domainCode,
    dataType: row.dataType,
    length: row.length,
    precision: row.precision,
    required: row.required,
    description: row.description,
    pattern: row.pattern,
    defaultValue: row.defaultValue,
    example: row.example
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据字典 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await dataDictionaryApi.delete(row.id)
    ElMessage.success('删除成功')
    loadDataDictionaries() // 重新加载数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除数据字典失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const editDataDictionary = (dictionary) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(formData, {
    id: dictionary.id,
    code: dictionary.code,
    name: dictionary.name,
    domainCode: dictionary.domainCode,
    dataType: dictionary.dataType,
    length: dictionary.length,
    precision: dictionary.precision,
    required: dictionary.required,
    description: dictionary.description,
    pattern: dictionary.pattern,
    defaultValue: dictionary.defaultValue,
    example: dictionary.example,
    status: dictionary.status
  })
}

const resetForm = () => {
  Object.assign(formData, {
    code: '',
    name: '',
    domainCode: '',
    dataType: '',
    length: null,
    precision: null,
    required: false,
    description: '',
    pattern: '',
    defaultValue: '',
    example: '',
    status: 'active'
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 构造后端需要的数据格式
    const saveData = {
      dictCode: formData.code,
      dictLabel: formData.name,
      dictType: formData.domainCode,
      dictValue: formData.defaultValue,
      remark: formData.description,
      isEnabled: formData.status === 'active'
    }
    
    if (isEdit.value) {
      // 编辑模式
      saveData.id = formData.id
      await dataDictionaryApi.update(saveData)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      await dataDictionaryApi.create(saveData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadDataDictionaries() // 重新加载数据
  } catch (error) {
    console.error('保存数据字典失败:', error)
    ElMessage.error('保存失败')
  } finally {
    submitting.value = false
  }
}

const toggleStatus = async (dictionary) => {
  try {
    await ElMessageBox.confirm(
      `确定要${dictionary.status === 'active' ? '禁用' : '启用'}数据字典 "${dictionary.name}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    dictionary.status = dictionary.status === 'active' ? 'inactive' : 'active'
    dictionary.updateTime = new Date().toLocaleString()
    ElMessage.success(`数据字典已${dictionary.status === 'active' ? '启用' : '禁用'}`)
  } catch {
    // 用户取消
  }
}

const deleteDataDictionary = async (dictionary) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据字典 "${dictionary.name}" 吗？删除后不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = dataDictionaries.value.findIndex(d => d.id === dictionary.id)
    if (index !== -1) {
      dataDictionaries.value.splice(index, 1)
      ElMessage.success('数据字典删除成功')
    }
  } catch {
    // 用户取消
  }
}

const loadDataDictionaries = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      dictType: selectedDomain.value || undefined,
      keyword: searchKeyword.value || undefined
    }
    
    const response = await dataDictionaryApi.getPage(params)
    if (response && response.records) {
      dataDictionaries.value = response.records.map(item => ({
        id: item.id,
        code: item.dictCode,
        name: item.dictLabel,
        domainCode: item.dictType,
        dataType: 'VARCHAR', // 后端暂无此字段，使用默认值
        length: null,
        precision: null,
        required: true,
        description: item.remark || '',
        pattern: '',
        defaultValue: item.dictValue || '',
        example: '',
        status: item.isEnabled ? 'active' : 'inactive',
        createTime: item.createTime,
        updateTime: item.updateTime
      }))
      pagination.total = response.total || 0
    }
  } catch (error) {
    console.error('加载数据字典失败:', error)
    ElMessage.error('加载数据字典失败')
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  loadDataDictionaries()
}

// 分页处理
const handlePageChange = (page) => {
  pagination.current = page
  loadDataDictionaries()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadDataDictionaries()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  loadDataDictionaries()
}

onMounted(() => {
  // 组件挂载时加载数据
  loadDataDictionaries()
})
</script>

<style scoped>
.data-dictionary-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.page-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  text-align: right;
}
</style>